package com.sangmo.fts.common.authority.filters;

import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.common.utils.UnderlineToCamelUtils;
import com.sangmo.fts.common.authority.EntitySearchContext;
import com.sangmo.fts.common.authority.IAuthorityFilter;
import com.sangmo.fts.common.authority.meta.UserAnn;
import com.sangmo.fts.common.authority.sql.NativeSearchContext;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

/*
* 当是指定用户时，具备读/写权限
* */
public class UserFilter implements IAuthorityFilter<UserAnn> {
    @Override
    public Class<UserAnn> getAnnotation() {
        return UserAnn.class;
    }

    @Override
    public IAuthorityFilter.SearchFilterResult internalSearchFilter(EntitySearchContext context, UserAnn annotation, int usedRight) {
        Root root = context.getRoot();
        CriteriaBuilder cb = context.getCriteriaBuilder();

        Long userId = (Long) UserSession.getUserInterface().getId();
        Path userPath = root.get(annotation.userId());

        return new SearchFilterResult().setPredicate(cb.equal(userPath, userId));
    }

    @Override
    public NativeSearchFilterResult internalNativeSearchFilter(NativeSearchContext context, UserAnn annotation, int expectedRight) {
        //a.? = :v
        Long userId = (Long)UserSession.getUserInterface().getId();
        String var = context.createVar();
        NativeSearchFilterResult result = new NativeSearchFilterResult();
        result.getVariables().put(var, userId);

        String sql = String.format("%s.%s = :%s"
                , context.getAlias(), UnderlineToCamelUtils.camelToUnderline(annotation.userId()), var);

        return result.setSql(sql);
    }
}
